package com.ray.service;

import com.ray.bean.*;
import com.ray.exception.ServiceException;
import com.ray.mapper.ApplyRepairFormMapper;
import com.ray.mapper.OrderCreateApplyMapper;
import com.ray.pojo.MyUser;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.StringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ApplyRepairFormService {
	@Autowired
	ApplyRepairFormMapper applyRepairFormMapper;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	StructureTreeService structureTreeService;
	@Autowired
	CompanyService companyService;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	OrderCreateApplyMapper orderCreateMapper;
	   
	
	/**
	 * 获取订单明细
	 * @param orderId(订单编号)
	 * @return
	 * @throws ServiceException
	 */
	public List<ApplyRepairFormBean> getOrderInfoDetail(Map map) {
		Assert.notNull(map.get("orderId"),"未获取到订单编号");
		List<ApplyRepairFormBean> detailList=applyRepairFormMapper.getOrderInfoDetail(map);
		Assert.isTrue(detailList!= null && detailList.size()>0,"该订单没有明细");
		return detailList;
	}


	/**
	 * 获取用户车间的用户
	 * @param map
	 * @return
	 */
	public List<UserBean> getWorkShopUser(MyUser myUser) {
		Assert.isTrue(myUser.getWorkShopId()!=null && !myUser.getWorkShopId().equals("") && !myUser.getWorkShopId().equals("0"),"登录用户没有所属车间，请去人事行政下的职员表设置车间");
		return applyRepairFormMapper.getWorkShopUser(myUser.getWorkShopId());
	}


	/**
	 * 获取登录人车间的用户
	 * @param applyArray(申补数组)
	 * @return
	 * @throws ServiceException
	 */
	public void createApplyRepairForm(Map map,MyUser myUser) {
		Assert.notNull(map.get("applyArray"),"未获取到参数");
		String applyArrayStr=map.get("applyArray").toString();
		JSONArray applyArray= JSONArray.fromObject(applyArrayStr);
		Map<String, Class> classMap = new HashMap<String, Class>(); 
		classMap.put("personLiableList", ApplayPersonLiableBean.class);
		List<ApplyRepairFormBean> applyRepairFormList=new ArrayList<ApplyRepairFormBean>();
		for(int i=0;i<applyArray.size();i++) {
			JSONObject jsonObject=applyArray.getJSONObject(i);
			ApplyRepairFormBean applyRepairFormBean=(ApplyRepairFormBean) jsonObject.toBean(jsonObject, ApplyRepairFormBean.class, classMap);
		    //必须要有物料代码
			Assert.isTrue(applyRepairFormBean.getMaterialCode()!=null && !applyRepairFormBean.getMaterialCode().equals(""),"物料信息不全");
		    //如果是损坏单必须要有责任人
			if(applyRepairFormBean.getType()==2)
		    	Assert.isTrue(applyRepairFormBean.getPersonLiableList()!=null && applyRepairFormBean.getPersonLiableList().size()>0,"损坏单必须要有责任人");
		    applyRepairFormBean.setId(StringUtil.getUUID());//设置id
		    applyRepairFormBean.setStatus(0);//设置状态
		    applyRepairFormBean.setWorkShopId(myUser.getWorkShopId());//设置申补单车间
		    for(ApplayPersonLiableBean person:applyRepairFormBean.getPersonLiableList()) {
		    	person.setId(StringUtil.getUUID());//设置人员信息id
		    	person.setApplyId(applyRepairFormBean.getId());//人员与申补单关联id
		    }
		    applyRepairFormList.add(applyRepairFormBean);
		}
		Assert.isTrue(applyRepairFormList!=null && applyRepairFormList.size()>0,"未获取到申补单数据");
	    map.put("applyRepairFormList", applyRepairFormList);
		applyRepairFormMapper.insertApplyRepairForm(map);
		/**
		 * 发送消息通知审核人
		 */
        sendTemplateMsg(map);
	}

	//发送模版推送消息
	public void sendTemplateMsg(Map map) {
		//避免推送消息出现问题导致订单审核和保存出现回滚
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = simpleDateFormat.format(new Date());
		String accessToken=weiXinService.getAccessToken(null);
		List<Map<String, String>> list=orderCreateMapper.getOpenIdForAudit(map.get("loginUserId").toString(),"5");
		for(int i=0;i<list.size();i++) {
			com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonWatiApproval("您有待审核的任务，请电脑端审核。",
					"物料申补单申请审核", map.get("loginUserName").toString(),
					list.get(i).get("phone"),time , "请尽快前往物料申补单查询审核", "", null, null, null, null, null, null, null);
			WeixinTemplateSender.sendWechatmsgToUser(list.get(i).get("openid"), "Ugl14MUqyvpWkHZPm9wuju_1tC_68FoLYfPV2muCvD0", "", data, accessToken);
		}
	}

	
	/**
	 * 获取申补单信息
	 * @param orderId(订单信息 可能是 系统订单编号，工厂型号，客户型号，公司订单编号等)
	 * @param materialDetail(物料信息 可能是 物料名称，规格型号，色号，供应商)
	 * @param status(状态  0未审核 1已审核 2已退回)
	 * @return 
	 * @throws ServiceException
	 */
	public  DatatablesViewPageBean<ApplyRepairFormBean> getApplyRepairForm(Map map) {
		DatatablesViewPageBean<ApplyRepairFormBean> datatablesViewPageBean = new DatatablesViewPageBean<ApplyRepairFormBean>();
		int count = applyRepairFormMapper.getApplyRepairFormCount(map);
		List<ApplyRepairFormBean> list  =  applyRepairFormMapper.getApplyRepairForm(map);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(list);
		return datatablesViewPageBean;
	}


	/**
	 * 删除申补单
	 * @param id(申补单id)
	 */
	public void deleteApplyRepairForm(Map map ) {
        Assert.isTrue(map.get("id")!=null,"未获取到id");		
        ApplyRepairFormBean applyRepairForm=applyRepairFormMapper.getApplyById(map.get("id").toString());
        Assert.isTrue(applyRepairForm != null ,"改申补单不存在");
        Assert.isTrue(applyRepairForm.getStatus()!=1 ,"改申补单已审核,不可删除");
        Assert.isTrue(map.get("loginUserId").toString().equals(applyRepairForm.getCreateUserId()),"只有制单人才能删除");
        applyRepairFormMapper.deleteApplyRepairForm(map);
        applyRepairFormMapper.deletePersonByApplyId(map);
	}


	
	/**
	 * 修改申补单
	 * @param id(申补单id)
	 * @param applyCount(修改数量)
	 * @return
	 * @throws ServiceException
	 */
	public void updateApplyRepairForm(Map map) {
		Assert.isTrue(map.get("id")!=null,"未获取到id");		
		Assert.isTrue(map.get("applyCount")!=null,"未获取到修改数");		
        ApplyRepairFormBean applyRepairForm=applyRepairFormMapper.getApplyById(map.get("id").toString());
        Assert.isTrue(applyRepairForm != null ,"改申补单不存在");
        Assert.isTrue(applyRepairForm.getStatus()!=1,"该申补单已审核，不可修改");
        Assert.isTrue(map.get("loginUserId").toString().equals(applyRepairForm.getCreateUserId()),"只有制单人才能删除");
        applyRepairFormMapper.updateApplyRepairForm(map);
	}


	/**
	 * 审核退回
	 * @param id(申补单id)
	 * @param status(状态)
	 * @param conpanyShare(公司占比)
	 * @return
	 * @throws ServiceException
	 */
	public void approvalApplyRepairForm(Map map, int status) {
		Assert.notNull(map.get("id"),"未获取到id");
		Assert.notNull(map.get("status"),"未获取到状态");
		Assert.notNull(map.get("conpanyShare"),"未获取到公司占比");
		map.put("type","5");   
		List<String> userIds = approvalService.getApprovalIdByLoginId(map);
		Assert.isTrue(null!=userIds && userIds.size()>0,"没有审批此申补单的权限");
		ApplyRepairFormBean applyRepairForm=applyRepairFormMapper.getApplyById(map.get("id").toString());
		Assert.isTrue(applyRepairForm!=null,"该申补单不存在");
		Assert.isTrue(applyRepairForm.getStatus()==0,"该申补单已审核或已退回，不可再次操作");
		if(status==1) {//审核通过
			 Assert.notNull(map.get("applyType"),"未获取到类型");
			 CompanyBean companyBean=companyService.getCompany(map);
			 int type=Integer.parseInt(map.get("applyType").toString());
			 //类型是损坏单要判断占比
			 if(type==2) {
				 if(companyBean.getStartShare()!=0) {
					 Assert.isTrue(Double.parseDouble(map.get("conpanyShare").toString())>=companyBean.getStartShare(),"公司占比不能小于"+companyBean.getStartShare()+"%");
				 }
				 if(companyBean.getEndShare()!=0) {
					 Assert.isTrue(Double.parseDouble(map.get("conpanyShare").toString())<=companyBean.getEndShare(),"公司占比不能大于"+companyBean.getEndShare()+"%");
				 }
			 }
//			 MaterialTreeBean materialTreeBean=structureTreeService.getMaterialTreeByMaterialType(applyRepairForm.getMaterialType());
			 Map<String,String> mateiralTypeMap = new HashMap<String,String>();
			 mateiralTypeMap.put("loginCompany", map.get("loginCompany").toString());
			 mateiralTypeMap.put("materialType", applyRepairForm.getMaterialType());
			 mateiralTypeMap.put("status","1");
			 CompanyMaterialTypeBean materialTreeBean =companyMaterialTypeService.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			 /**
			  * 如果此物料设置了不读取颜色
			  */
			 if(null!=materialTreeBean && materialTreeBean.getIsReadColor()==2) {
				 applyRepairForm.setColor(null);
				 applyRepairForm.setColorDescription(null);
			 }
			 String feedMainId="";
			 List<String> feedMainIdList=applyRepairFormMapper.getFeedMainIdByOrderId(applyRepairForm.getOrderId());
			 //如果此订单已存在投料单
			 if(feedMainIdList!=null && feedMainIdList.size()>0) {
				feedMainId=feedMainIdList.get(0);
			 }else {
				feedMainId=StringUtil.getUUID();
				applyRepairFormMapper.insertFeedMain(feedMainId,applyRepairForm.getOrderId(),map.get("loginCompany").toString());
			 }
			 map.put("mainId", feedMainId);
			 map.put("detailId", StringUtil.getUUID());
			 map.put("applyRepairForm", applyRepairForm);
			 applyRepairFormMapper.insertFeedDeatil(map);
		}
		applyRepairFormMapper.approvalApplyRepairForm(map);
	}
	
}
